//
//  NewsDetailViewController.swift
//  osc
//
//  Created by admin on 14/10/31.
//  Copyright (c) 2014年 sinosun. All rights reserved.
//

import UIKit

class NewsDetailViewController: UIViewController {
    var id: Int = 0
    var newsDetailMV: NewsDetailMV?

    @IBOutlet var webview: UIWebView!
    
    
    @IBOutlet var barButton_header: UIBarButtonItem!
    @IBOutlet var barButtonItem1: UIBarButtonItem!

    @IBOutlet var barButtonItem2: UIBarButtonItem!
    
    @IBOutlet var barButtonItem3: UIBarButtonItem!
    
    @IBOutlet var barButtonItem4: UIBarButtonItem!
    
    @IBOutlet var barbutton_tail: UIBarButtonItem!
    @IBOutlet var toolBar: UIToolbar!
    
    var activityViewController:UIActivityViewController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        println(id)
      //  setBarButtons()
        hiddenTabBar()
        setToolbar()
        
        var parameters = ["id":id, "access_token": access_token, "dataType":"json"]

        HttpClient.loadData(api_news_detail, parameters: parameters,
            success: { () -> Void in
            self.webview.loadHTMLString(self.newsDetailMV?.toHtml(self.newsDetailMV!), baseURL: nil)
            var favourite = self.newsDetailMV?.favourite
                println("favourite=\(favourite)")
                if favourite == 1 {
                    println("已收藏")
                    self.barButtonItem2.image = UIImage(named: "favourite")
                }else if favourite == 0{
                    println("未收藏")
                    self.barButtonItem2.image = UIImage(named: "favourite_blank")

                }else {
                    println("dddd")
                }
                
        }) { (data) -> Void in
            var newsDetailM = NewsDetailM(JSONDecoder(data))
            self.newsDetailMV = NewsDetailMV(newDetail: newsDetailM)
        }
    }
    

    @IBAction func nextPage(sender: AnyObject) {
        self.id--
        var parameters = ["id":self.id, "access_token": access_token, "dataType":"json"]
        loadData(parameters)
    }
    
    func loadData(parameters: [String:AnyObject]){
        HttpClient.loadData(api_news_detail, parameters: parameters, success: { () -> Void in
            self.webview.loadHTMLString(self.newsDetailMV?.toHtml(self.newsDetailMV!), baseURL: nil)
            }) { (data) -> Void in
               // println(data.length)
                var str = NSString(data: data, encoding: NSUTF8StringEncoding)
                println(str)
                if data.length == 0 {
                    self.id--
                    var parameters = ["id":self.id, "access_token": access_token, "dataType":"json"]
                    self.loadData(parameters)
                }else{
                    var newsDetailM = NewsDetailM(JSONDecoder(data))
                    self.newsDetailMV = NewsDetailMV(newDetail: newsDetailM)
                }
        }
    }
    @IBAction func setFavourite(sender: AnyObject) {
        //println("setFavourite")
        //performSegueWithIdentifier("favourite", sender: nil)
        println("收藏之前先判断是否登陆")
        var accessToken: Tokencc? = TokenManager.listToken()
        
        
        if accessToken == nil || !TokenManager.checkToken(accessToken!) {
            performSegueWithIdentifier("favourite", sender: sender)
        }else{
            println("已登陆，添加收藏")
            addFavourite()
            var favourite = self.newsDetailMV?.favourite
            println("favourite=\(favourite)")
            if favourite == 1 {
                println("已收藏,要取消收藏")
                removeFavourite()

            }else if favourite == 0{
                println("未收藏,添加收藏")
                addFavourite()
            }else {
                println("dddd")
            }

            
            
            
        }
    }
    
    func addFavourite(){
        var parameters = ["access_token":access_token, "id": self.id,"type":4, "dataType":"json"]
        HttpClient.loadData(api_favorite_add, parameters: parameters, success: { () -> Void in
            self.barButtonItem2.image = UIImage(named: "favourite")
            }, phaser: { (data) -> Void in
                var temp = NSString(data: data , encoding: NSUTF8StringEncoding)
                println("temp =\(temp)")
                var favouriteOperation: FavouriteOperation = FavouriteOperation(JSONDecoder(data))
                if favouriteOperation.error == "200"{
                    println("收藏成功")
                }else{
                    println("收藏失败")
                }
        })
    }
    
    func removeFavourite(){
        var parameters = ["access_token":access_token, "id": self.id,"type":4, "dataType":"json"]
        HttpClient.loadData(api_favorite_remove, parameters: parameters, success: { () -> Void in
            self.barButtonItem2.image = UIImage(named: "favourite_blank")
            }, phaser: { (data) -> Void in
                var temp = NSString(data: data , encoding: NSUTF8StringEncoding)
                println("temp =\(temp)")
                var favouriteOperation: FavouriteOperation = FavouriteOperation(JSONDecoder(data))
                if favouriteOperation.error == "200"{
                    println("取消收藏成功")
                }else{
                    println("取消收藏失败")
                }
        })
    }

    
    @IBAction func share(sender: AnyObject) {
        println("share")
        //var title = self.newsDetailMV?.title!
        
        activityViewController = UIActivityViewController(activityItems: ["", ""], applicationActivities: nil)
        
        presentViewController(activityViewController,
            animated: true,
            completion: {
        })
        
    }

    
    @IBAction func comment(sender: AnyObject) {
        performSegueWithIdentifier("comment", sender: sender)
    }


    func hiddenTabBar(){
        self.tabBarController?.tabBar.hidden = true
    }
    
    func setToolbar(){
        //self.toolbarItems =
         self.toolBar.backgroundColor = UIColor.whiteColor()
        
        var barButtonItem_space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
        barButtonItem_space.width = 50
        
        var tabbars: [UIBarButtonItem]! = [barButton_header,barButtonItem1,barButtonItem_space,
            barButtonItem2, barButtonItem_space,barButtonItem3,barButtonItem_space, barButtonItem4,barbutton_tail]
        
        
        self.toolBar.items = tabbars
        
    }
    
    func barButtonItemClicked(sender: AnyObject){
        println("barButtonItemClicked")
    }
    
    func setBarButtons(){
        var rigthBarButtonItem = UIBarButtonItem(title: "收藏此文", style: UIBarButtonItemStyle.Bordered, target: self, action: "favoriteClicked:")
        self.navigationItem.rightBarButtonItem = rigthBarButtonItem
    }
    
    


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
//        println("-----rrrr=\(segue.identifier)")
        var identifier = segue.identifier!
        if identifier == "favourite"{
            
        }else if identifier == "comment"{
            var target = segue.destinationViewController as CommontTableViewController
            println("将id传到下个页面")
            var id = self.newsDetailMV?.id
            target.setValue(id, forKey: "id")
        }
        
    }
    

}
